package com.example.springbootweb.test;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.server.auth.DigestAuthenticationProvider;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;


/**
 * @Description: ZkAuth
 * @Author: mingtian
 * @CreateDate: 2019/9/23 13:52
 * @Version: 1.0
 */
public class ZkAuth {

    /**
     * 连接地址
     */
    public static final String IP_ADRESS = "127.0.0.1:2181";

    /**
     * 连接超时时间
     */
    public static final int TIMEOUT = 5000;

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException, NoSuchAlgorithmException {
        //1.建立 zk 连接
        ZooKeeper zk = new ZooKeeper(IP_ADRESS, TIMEOUT, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println(event.getState().name());
            }
        });

        //2.创建账号权限 admin 可以实现读、写、删除、创建、admin操作
        Id id1 = new Id("digest", DigestAuthenticationProvider.generateDigest("admin:admin123"));
        ACL acl1 = new ACL(ZooDefs.Perms.ALL, id1);

        //创建权限  guest 只允许读的操作
        Id id2 = new Id("digest", DigestAuthenticationProvider.generateDigest("guest:guest123"));
        ACL acl2 = new ACL(ZooDefs.Perms.READ, id2);

        // 存放用户信息
        ArrayList<ACL> acls = new ArrayList<>();
        acls.add(acl1);
        acls.add(acl2);


        //3.创建临时节点 无序     并对用户进行授权
        String s = zk.create("/eureka1", "http://127.0.0.1:8080".getBytes(), acls, CreateMode.PERSISTENT);
        zk.create("/eureka1/order", "http://12.0.0.1:8081".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        zk.create("/eureka1/member", "http://12.0.0.1:8082".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        System.out.println("acl:" + s);

        // 4.设置 zk 连接账号
        zk.addAuthInfo("digest", "guest:guest123".getBytes());

        //5.根据 path 查询内容
//        byte[] data = zk.getData("/eureka", null, new Stat());
//        String s1 = new String(data);
//        System.out.println("获取数据:" + s1);

        //6.休眠 3 秒  关闭 zk 连接
        Thread.sleep(3000);
        //zk.close();
    }
}